package com.zyk.leetcode;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;

/**
 * @author zhangsan
 * @date 2021/4/7 11:07
 */
public class C1115 {

    static class FooBar {
        private int n;

        private BlockingQueue<Byte> countQueue1, countQueue2;

        public FooBar(int n) {
            this.n = n;
            countQueue1 = new SynchronousQueue<>();
            try {
                countQueue1.put((byte) 1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countQueue2 = new SynchronousQueue<>();
        }

        public void foo(Runnable printFoo) throws InterruptedException {
            for (int i = 0; i < n; i++) {
                countQueue1.take();
                // printFoo.run() outputs "foo". Do not change or remove this line.
                printFoo.run();
                countQueue2.put((byte) 1);
            }
        }

        public void bar(Runnable printBar) throws InterruptedException {

            for (int i = 0; i < n; i++) {
                countQueue2.take();
                // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();
                countQueue1.put((byte) 1);
            }
        }
    }


    // for test
    public static void main(String[] args) {
        FooBar fooBar = new FooBar(5);

        try {
            fooBar.foo(() -> {
                System.out.print("foo");
            });
            fooBar.bar(() -> {
                System.out.print("bar");
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
